package com.talent.jiwen.my;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.http.common.ApiRetrofit;
import com.talent.jiwen.util.MyToast;
import com.talent.jiwen.util.QRCodeUtil;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MyQRCodeActivity extends BaseActivity {

    @BindView(R.id.studentQrCodeIv)
    ImageView studentQrCodeIv;
    @BindView(R.id.studentSaveTv)
    TextView studentSaveTv;

//    @BindView(R.id.teacherQrCodeIv)
//    ImageView teacherQrCodeIv;
//    @BindView(R.id.teacherSaveTv)
//    TextView teacherSaveTv;

    private Bitmap studentBitmap;
//    private Bitmap teacherBitmap;

    private static final int TYPE_TEACHER = 1;
    private static final int TYPE_STUDENT = 2;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_qrcode;
    }

    @Override
    public String titleName() {
        return "邀请二维码";
    }

    @Override
    protected void initData() {
        String EDU_URL = ApiRetrofit.EDU_WEB_URL;
        String studentInvisitUrl=EDU_URL+"/customerIndex/studentInviteAndReg?code="+ SPUtil.stringOut(SPConstant.INVITE_CODE)+"&name="+SPUtil.getUserName();
//        String teacherInvisitUrl = EDU_URL + "/customerIndex/teacherInviteAndReg?code=" + SPUtil.stringOut(SPConstant.INVITE_CODE) + "&name=" + SPUtil.getUserName();

        initStudentCode(studentInvisitUrl);
//        initTeacherCode(teacherInvisitUrl);

    }

    /**初始化学生二维码
     *
     * @param studentInvisitUrl
     */
    private void initStudentCode(String studentInvisitUrl){
        Bitmap codeBitmap = QRCodeUtil.createQRCodeBitmap(studentInvisitUrl, 500, 500);
        studentBitmap =  QRCodeUtil.addLogo(codeBitmap , BitmapFactory.decodeResource(this. getResources(), R.mipmap.ic_launcher));
        studentQrCodeIv.setImageBitmap(studentBitmap);
        if (studentBitmap != null){
            studentSaveTv.setVisibility(View.VISIBLE);
        }else{
            studentSaveTv.setVisibility(View.GONE);
        }

        studentSaveTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(null != studentBitmap){
                    saveImageToGallery(MyQRCodeActivity.this , studentBitmap , TYPE_STUDENT);
                }else{
                    showToast("二维码未生成");
                }
            }
        });
    }

    /**初始化老师二维码
     *
     * @param teacherInvisitUrl
     */
//    private void initTeacherCode(String teacherInvisitUrl){
//        Bitmap codeBitmap = QRCodeUtil.createQRCodeBitmap(teacherInvisitUrl, 450, 450);
//        teacherBitmap =  QRCodeUtil.addLogo(codeBitmap , BitmapFactory.decodeResource(this. getResources(), R.mipmap.ic_teacher_logo));
//        teacherQrCodeIv.setImageBitmap(teacherBitmap);
//        if (teacherBitmap != null){
//            teacherSaveTv.setVisibility(View.VISIBLE);
//        }else{
//            teacherSaveTv.setVisibility(View.GONE);
//        }
//
//        teacherSaveTv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if(null != teacherBitmap){
//                    saveImageToGallery(MyQRCodeActivity.this , teacherBitmap , TYPE_TEACHER);
//                }else{
//                    showToast("二维码未生成");
//                }
//            }
//        });
//    }
    /**
     * 保存图片到相册
     *
     * @param context
     * @param bmp
     */
    public void saveImageToGallery(Context context, Bitmap bmp , int type) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            MyToast.show(context, "sdcard未使用");
            return;
        }
        // 首先保存图片
        File appDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsoluteFile();
        if (!appDir.exists()) {
            appDir.mkdir();
        }

//        String fileName = System.currentTimeMillis() + ".jpg";
        String fileName = "";
        if (type == TYPE_TEACHER){
            fileName =  SPUtil.getBSUId() + "老师邀请码" + System.currentTimeMillis() +".jpg";
        }else{
            fileName =  SPUtil.getBSUId() + "学生邀请码" + System.currentTimeMillis() +".jpg";
        }

        File file = new File(appDir, fileName);
        if(file.exists()){
            showToast("二维码已保存");
        }else{
            try {
                FileOutputStream fos = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                MyToast.show(context, "保存失败");
                e.printStackTrace();
                return;
            } catch (IOException e) {
                MyToast.show(context, "保存失败");
                e.printStackTrace();
                return;
            }
            // 其次把文件插入到系统图库
// try {
// MediaStore.Images.Media.insertImage(context.getContentResolver(),
// file.getAbsolutePath(), fileName, null);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
            MyToast.show(context, "保存成功 , 请到相册查看");
// 最后通知图库更新
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
        }

    }
}
